import { httpRequest } from '@/api/common.ts'

export const props = {
  value: {
    type: [String, Number, Array],
    default: '',
  },
  column: {
    type: Object,
    default: () => ({}),
  },
}

export const mixin = {
  watch: {
    column: {
      handler(newVal) {
        this.initOptions(newVal)
        this.initProps(newVal)
      },
      immediate: true,
      deep: true,
    },
    value: {
      handler(newVal) {
        this.val = newVal
      },
      immediate: true,
    },
  },
  computed: {
    url() {
      return this.column.async?.url
    },
    initRequest() {
      return this.column?.async?.initRequest
    },
    method() {
      return this.column?.async?.method || 'get'
    },
    multiple() {
      return this.column?.multiple
    },
    fetchSearch() {
      return this.column?.async?.fetchSearch
    },
    keyword() {
      return this.column.async?.searchKey || 'keyword'
    },
    optionList() {
      return this.column.async?.data
    },
    reqBody() {
      return this.column.async?.reqBody || {}
    },
  },
  data() {
    return {
      option: [],
      props: {
        label: 'label',
        value: 'value',
      },
    }
  },
  methods: {
    // 初始化下拉数据
    initOptions(data) {
      if (this.url && this.fetchSearch) {
        this.fetchOptions(data)
        return false
      }

      const option = data.options
      if (option && Array.isArray(option) && option.length > 0) {
        this.option = option
      }
    },
    // label 和value 初始化
    initProps(data) {
      const props = data.props
      // 获取默认值的key
      const keys = Object.keys(this.props)
      if (
        props &&
        Object.prototype.toString.call(props) === '[object Object]'
      ) {
        for (const key in props) {
          if (keys.includes(key)) {
            this.props[key] = props[key]
          }
        }
      }
    },
    // 异步请求
    fetchOptions(data) {
      if (!this.initRequest) return false
      this.getOptions()
    },
    // 获取option
    async getOptions(value) {
      if (
        this.optionList &&
        Object.prototype.toString.call(this.optionList) === '[object Function]'
      ) {
        this.option = await this.optionList()
        return
      }
      // if (this.selectData.length > 0) {
      //   this.option = this.selectData
      //   return
      // }
      const req = { url: this.url, method: this.method }
      if (this.method === 'post')
        req.data = { ...this.reqBody, ...{ [this.keyword]: value } } || {}
      if (this.method === 'get') req.params = { [this.keyword]: value } || {}

      httpRequest(req).then((resp) => {
        this.option = resp.data
      })
    },
    keywordSearch(query) {
      this.getOptions(query)
    },

    handleChange(val) {
      this.$emit('update:value', val)
      this.column.callback && this.column.callback(val)
    },
  },
}
